/*
 * AutoSetup tool
 *
 * License: LGPL v3
 */
package org.passwordstore.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author thotheolh
 */
public class AutoSetup {

    Connection conn = null;
    boolean table_exist = false;

    public AutoSetup(Connection connection) {
        if (connection != null) {
            this.conn = connection;
        } else {
            //System.out.println("Connection is null !");//Diagnostics
        }
    }

    /**
     * Check if rewquired database table is existing
     * @return int, status code
     * @throws SQLException
     */
    public int isTablesExist() throws SQLException {//Checks if dbDir database exists and what status it exist in.
        int status = -1; //0 - no table or fragments of table, 1 - full fledge database, -1 - error
        try {
            PreparedStatement pstmt = conn.prepareStatement("SHOW TABLES");
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String tableName = rs.getString("TABLE_NAME");
//                    System.out.println("Found Table: " + tableName);
                checkTables(tableName);
            }
            if (table_exist == true) {
                return status = 1;
            } else {
                return status = 0;
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return status;
    }

    /**
     * Setup database tables if not existing.
     */
    public void setup() {//Setup dbDir database.
            try {
                String statement = "CREATE CACHED TABLE PUBLIC.PASSWORDSTORE(USERNAME VARCHAR(1000) NOT NULL," +
                        "PASSWORD VARCHAR(1000) NOT NULL," +
                        "REQUIRED_PLACE VARCHAR(1000) NOT NULL);" +
                        "ALTER TABLE PUBLIC.PASSWORDSTORE ADD CONSTRAINT PUBLIC.PASSWORDSTORE_PK PRIMARY KEY(USERNAME, PASSWORD, REQUIRED_PLACE)";
                PreparedStatement pstmt = conn.prepareStatement(statement);
                int exNum = pstmt.executeUpdate();
                if (exNum >= 1) {
                    //System.out.println("Setup: " + exNum + " - Setup successfully completed !");//Diagnostics
                    conn.commit();
                }
                //System.out.println("Setup done...");//Diagnostics
            } catch (SQLException ex) {
                Logger.getLogger(AutoSetup.class.getName()).log(Level.SEVERE, null, ex);
            }
    }

    /**
     * Main init method
     */
    public void init() {
        try {
            int dbStats = this.isTablesExist();
            if (dbStats == 0) {
                //System.out.println("Attempting to adjust database...");//Diagnostics
                this.setup();
                if (this.isTablesExist() == 1) {
                    //System.out.println("System Database OK !");//Diagnostics
                } else {
                    //System.out.println("(!): Failed to adjust system database properly...");//Diagnostics
                }
            } else if (dbStats == 1) {
                //System.out.println("System Database OK !");//Diagnostics
            } else {
                //System.out.println("(!): System Database have some ERRORS ! Trying to go on despite error(s)...");//Diagnostics
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Check table names
     * @param tableName
     */
    public void checkTables(String tableName) {
        if (tableName.equalsIgnoreCase("PASSWORDSTORE")) {
            table_exist = true;
        }
    }
}
